#!/bin/bash -e
# hmmcopy simu

function info() {
echo Program: hmmcopy simu
echo Usage: `basename $0` "[-w window_size] [-b asemmbly] <in.bam>"
exit 65
}

while getopts  ":w:c:p:b:f:" opts
do
	case  $opts  in
	w)
		window=$OPTARG
		;;
	b)
        asemmbly=$OPTARG
        ;;
	c)
        chr=$OPTARG
        ;;
	\?) info;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then info; exit 1
fi


#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------


if [ -z "$window" ]; then
	window=200000
fi

if [ -z "$chr" ]; then
	chr=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y
fi


if
samtools view -H $1 |grep '^@RG'
then
sample_name=`samtools view -H $1 |grep '^@RG' |perl -n -e 'if(/SM:(.+?)[\t|\n]/){print $1}'`
fi
echo $sample_name

chrom=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y
echo $chrom
:<<!
# -------------------------

cp ${tools_path}/matlab/rc_simu.m .

cat $out_prefix.$window.sample.wig |awk '{if(/^f/){print "-1"}else{print}}' > 1.rc.txt

echo;echo;echo matlab should run foreground'!'
matlab -nojvm -r "rc_simu; quit;"

# cat 1.rc_simu.txt |awk 'BEGIN{chr="'$chrom'"; split(chr, chr1, ","); i=0}{if(/^-/){i++; print "fixedStep chrom=" chr1[i] " start=1 step=200000 span=200000"}else{print}}' > $out_prefix.$window.sample.simu.wig

paste $out_prefix.$window.sample.wig 1.rc_simu.txt > 1.merge.wig.txt

cat 1.merge.wig.txt |awk -F "\t" '{if(/^f/){print $1}else{print $2}}' > $out_prefix.$window.sample.simu.wig

# -------------------------
!

sample_name1=${sample_name}

Rscript ${tools_path}/script/hmmcopy0929.r --args \
$out_prefix.$window.sample.wig \
$sample_name1 \
$ref_genome.gc.$window.wig \
$ref_genome.map100bp.${window}.wig \
$chr

mv 1.cnv.hmmcopy.pdf $sample_name.cnv.hmmcopy.$window.pdf